package com.java.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.config.ExcelLisenters;
import com.java.mapper.DictMapper;
import com.java.model.cmn.Dict;

import com.java.model.vo.cmn.DictEeVo;
import com.java.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;


    /**根据parent_id查询子集
     * 添加缓存
     * @param id
     * @return
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")//添加缓存 dict指定的名字 key:keyGenerator是包名+方法名规则
    @Override
    public List<Dict> findChildById(Long id) {
        //可以根据该id查询parentId下的第一级的元素 传 1
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dcts = dictMapper.selectList(wrapper);

        dcts.forEach(item->{
            //得到一级的 id 去查他下面的子元素是否存在
            Boolean bool = hasChildren(item.getId());
            item.setHasChildren(bool);
        });
        return dcts;
    }

    //查询父元素下是否还有子元素 10000
    private Boolean hasChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = dictMapper.selectCount(wrapper);
        return count>0; //结果如果是0>0 返回 false
    }

    @Override
    public void exporExcel(HttpServletResponse response) {
        //设置下载信息
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xls");
            List<Dict> list = dictMapper.selectList(null);
            ArrayList<DictEeVo> arrayList = new ArrayList<>();
            //list 是dict类 我们需要导出后的数据 是dictVo类 需要遍历list集合 将数据设置给ditcvo
            for (Dict dict : list) {
                DictEeVo dictVo = new DictEeVo();
                BeanUtil.copyProperties(dict,dictVo);
                arrayList.add(dictVo);
            }
            //response.getOutputStream()
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(arrayList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * allEntries ：方法调用后清空指定的缓存
     * @param file
     */
    @CacheEvict(value = "dict",allEntries = true)
    @Override
    public void importExcel(MultipartFile file) {
        try {
            //简单导入
            EasyExcel.read(file.getInputStream(),Dict.class,new ExcelLisenters()).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String findName(String dictCode, String value) {
        if(StringUtils.isEmpty(dictCode)){
            //如果didctCode为空
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = dictMapper.selectOne(wrapper);
            return dict.getName();
        }else{
            //如果dictCode 不为空
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("dict_code",dictCode);
            //查询出dict_code这个dict元素
            Dict dict = dictMapper.selectOne(wrapper);
            //查询出他的id
            Long parent_id = dict.getId();

            //根据 parent_id 查询
            QueryWrapper<Dict> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("value",value);
            wrapper2.eq("parent_id",parent_id);
            Dict dict1 = dictMapper.selectOne(wrapper2);
            return dict1.getName();
        }
    }

    /**
     * 级联选择器的方法 参考 关键 hasChildren() 这个方法
     * @param typeCode
     * @return
     */
    @Override
    public List<Dict> findNameAndChild(String typeCode) {
        //通过父typeCode查询父级数据
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("value",typeCode);
        Dict dict = dictMapper.selectOne(wrapper);
        //通过父级id查询出该父级下所有子集的数据
        List<Dict> childData = this.findChildById(dict.getId());
        return childData;
    }

    @Override
    public List<Dict> findNameChildren(String typeCode) {
        //通过父typeCode查询父级数据
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",typeCode);
        Dict dict = dictMapper.selectOne(wrapper);
        //通过父级id查询出该父级下所有子集的数据
        List<Dict> childData = this.findChildById(dict.getId());
        return childData;
    }
}
